<template>
  <view class="wallet-page">
    <up-navbar title="我的钱包" @rightClick="rightClick" :titleStyle="{color: '#333333' , fontWeight: '500' ,
      fontSize:'34rpx'}" rightText="历史记录" :autoBack="true">
    </up-navbar>
    <view class="wallet-content">
      <view class="content-head">
        <image src="@/static/my/icon/balance.png" mode="" class="head-img"></image>
        <view class="head-name">{{labelConmitList.name}}</view>
        <view class="head-price">
          {{isExpert?userInfo.coins:userInfo.money}}
          <view class="price-label">金币</view>
        </view>
      </view>
      <view class="content-nav">
        <view class="nav-title">
          <view class="title-name">{{labelConmitList.title}}</view>
        </view>
        <view class="nav-box">
          <view :class="moneyActive === item.title? 'box-active' :'box'" v-for="item,index in moneyList" :key="index"
            @click="onPayChange(item)">{{item.title}}
          </view>
        </view>
        <view class="box-int" v-if="!isIos">
          <up-input :placeholder="labelConmitList.inputPlaceholder" type="number" color="#333333" v-model="intValue"
            border="none" @focus="moneyActive = 0" @blur="onblur">
            <template #prefix>
              <up-text text="其他金额" margin="0 32rpx 0 0" color="#333333" type="tips"></up-text>
            </template>
            <template #suffix v-if="isExpert">
              <up-text text="全部提现" color="#A4682F" size="26rpx" @click="onAmounts"></up-text>
            </template>
          </up-input>
        </view>
        <view class="nav-title" v-if="!isIos">
          <view class="title-name">{{labelConmitList.payName}}</view>
        </view>
        <view class="content-pay" v-if="!isIos">
          <up-radio-group v-model="payRadio" placement="row" iconPlacement="right">
            <view class="pay-nav" v-for="(item, index) in payList" :key="index" @click="groupChange(item.name)">
              <image :src="item.icon" mode="" class="pay-icon"></image>
              <view class="pay-info">
                <view class="pay-name">{{item.name}}</view>
                <view class="pay-num" v-if="!isIos">{{userInfo.alipay}}</view>
                <view class="text-label" @click="toBind" v-if="!isIos">{{userInfo.alipay?'换绑':'去绑定'}}</view>
              </view>
              <up-radio activeColor="#A4682F" :name="item.name">
              </up-radio>
            </view>
          </up-radio-group>
        </view>
        <view class="nav-prompt" v-if="!isExpert">
          <view class="prompt-title">金币说明</view>
          <view class="prompt-nav">
            购买的金币仅用于平台内消费，不可提现。
          </view>
        </view>
        <view class="pay-btn">
          <up-checkbox :customStyle="{marginBottom: '8px'}" shape="circle" activeColor="#A4682F" name="agree" usedAlone
            v-model:checked="aloneChecked" v-if="!isExpert">
            <template #label>
              <view class="agreement-title">
                我已阅读并同意
                <view class="agreement-label" @click.stop="toRecharge">《充值协议》</view>
              </view>
            </template>
          </up-checkbox>
          <up-button :text="labelConmitList.btnText + payValue" shape="circle" color="#A4682F"
            @click="onPay"></up-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    applePay,
    applepay,
    info,
    withdraw
  } from '../api.js'
  import {
    ref,
    reactive
  } from 'vue'
  import {
    Iap,
    IapTransactionState
  } from "./iap.js"
  import {
    onLoad,
    onShow
  } from '@dcloudio/uni-app'
  const moneyActive = ref(0)
  const payValue = ref('')
  const intValue = ref('')
  const isExpert = ref(false)
  const aloneChecked = ref(true)
  const isIos = ref(false)
  const productId = ref('')
  const loading = ref(false)
  const userInfo = ref({})
  const moneyList = ref([{
    title: '10'
  }, {
    title: '50'
  }, {
    title: '100'
  }, {
    title: '300'
  }, {
    title: '500'
  }, {
    title: '1000'
  }])
  const iap = new Iap({
    products: ['156067157101', '156067157102', '156067157103', '156067157104', '156067157105',
      '156067157106'
    ] // 苹果开发者中心创建
  })
  const labelConmitList = ref({
    name: '我的余额',
    title: '选择充值金额',
    inputPlaceholder: '请输入充值金额',
    payName: '请选择支付方式',
    payLabel: '充值遇到问题？',
    btnText: '充值'
  })
  const payRadio = ref('支付宝');
  const payList = ref([{
    name: '支付宝',
    icon: '/static/my/icon/zfb.png',
    id: 1
  }])

  onLoad(() => {
    userInfo.value = uni.getStorageSync('user')
    isExpert.value = uni.getStorageSync('user').is_expert === 1 ? true : false
    if (isExpert.value) {
      isIos.value = false
      payList.value = [{
        name: '支付宝',
        icon: '/static/my/icon/zfb.png',
        id: 1
      }]
      moneyList.value = [{
        title: '10'
      }, {
        title: "50"
      }, {
        title: '100',
      }]
      labelConmitList.value = {
        name: '我的收益',
        title: '选择提现金额',
        inputPlaceholder: '请输入提现金额',
        payName: '选择提现账户',
        payLabel: '提现遇到问题？',
        btnText: '提现'
      }
    } else {
      // #ifdef APP-PLUS
      uni.getSystemInfo({
        success(res) {
          if (res.osName == 'ios') {
            isIos.value = true
            init()
          }
        }
      })
      // #endif
    }
  })
  onShow(() => {
    infoApi()
  })

  function onAmounts() {
    intValue.value = userInfo.value.coins
    payValue.value = userInfo.value.coins
  }

  function onPay() {
    if (isExpert.value) {
      if (!payValue.value) {
        uni.showToast({
          title: '请选择提现金额',
          icon: 'none'
        })
        return
      }
      if (!userInfo.value.realname && !userInfo.value.idcard) {
        uni.showToast({
          title: '请先进行实名认证',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/my/otherFunctionPage/authenticationName'
          })
        }, 300)
        return
      } else if (!userInfo.value.alipay) {
        uni.showToast({
          title: '请先绑定支付宝',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/my/walletPage/walletAccount'
          })
        }, 300)
        return
      }
    } else {
      if (!payValue.value) {
        uni.showToast({
          title: '请选择充值金额',
          icon: 'none'
        })
        return
      }
      if (!aloneChecked.value) {
        uni.showToast({
          title: '请阅读并同意《充值协议》',
          icon: 'none'
        })
        return
      }
      if (isIos.value) {
        payment()
      }
    }
  }

  function toBind() {
    if (userInfo.value.realname && userInfo.value.idcard) {
      uni.navigateTo({
        url: '/pages/my/walletPage/walletAccount'
      })
    } else {
      uni.showToast({
        title: '请先进行实名认证',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/my/otherFunctionPage/authenticationName'
        })
      }, 300)
    }
  }

  function groupChange(val) {
    payRadio.value = val
  }

  function onPayChange(item) {
    if (uni.getSystemInfoSync().platform === 'ios') {
      productId.value = item.productid
      intValue.value = ''
      moneyActive.value = item.title
      payValue.value = item.title
    } else {
      intValue.value = ''
      moneyActive.value = item.title
      payValue.value = item.title
    }
  }

  function onblur(val) {
    if (val === '') {
      payValue.value = 0
    } else {
      payValue.value = val
    }
  }

  function rightClick() {
    uni.navigateTo({
      url: '/pages/my/walletPage/rechargeRecord'
    })
  }
  const infoApi = (async () => {
    const res = await info()
    if (res && res.code === 1) {
      userInfo.value = res.data
      uni.setStorageSync("user", res.data)
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none"
      })
    }
  })

  function toRecharge() {
    uni.navigateTo({
      url: '/pages/my/agreementPage/recharge-agreement'
    })
  }


  //ios 内购
  const init = (async () => {
    uni.showLoading({
      title: '检测支付环境...'
    })

    try {
      // 初始化，获取iap支付通道
      await iap.init()
      // 从苹果服务器获取产品列表
      const data = await iap.getProduct()
      data.forEach(item => {
        const numericValue = parseInt(item.title.replace(/[^0-9]/g, ''))
        item.title = numericValue
      })
      moneyList.value = data.sort((a, b) => a.price - b.price)
      moneyList.value[0].checked = true
      productId.value = moneyList.value[0].productid
    } catch (e) {
      uni.showModal({
        title: "init",
        content: e.mehttssage,
        showCancel: false
      })
    } finally {
      uni.hideLoading()
    }

    if (iap.ready) {
      restore()
    }
  })
  const restore = (async () => {
    // 检查上次用户已支付且未关闭的订单，可能出现原因：首次绑卡，网络中断等异常

    // 在此处检查用户是否登陆

    uni.showLoading({
      title: '正在检测已支付且未关闭的订单...'
    });

    try {
      // 从苹果服务器检查未关闭的订单，可选根据 username 过滤，和调用支付时透传的值一致
      let transactions = await iap.restoreCompletedTransactions({
        username: ""
      });
      //类型检查+ 安全转换
      if (typeof transactions !== 'string') {
        transactions = JSON.stringify(transactions)
      }
      if (!transactions.length) {
        return
      }

      // 开发者业务逻辑，从服务器获取当前用户未完成的订单列表，和本地的比较
      // 此处省略
      switch (transaction.transactionState) {
        case IapTransactionState.purchased:
          // 用户已付款，在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
          //let result = await this.validatePaymentResult();

          // 验证通过，交易结束，关闭订单
          // if (result) {
          //   await this.iap.finishTransaction(transaction);
          // }
          break;
        case IapTransactionState.failed:
          // 关闭未支付的订单
          await iap.finishTransaction(transaction);
          break;
        default:
          break;
      }
    } catch (e) {
      uni.showModal({
        content: e.message,
        showCancel: false
      })
    } finally {
      uni.hideLoading()
    }
  })
  const payment = (async () => {
    if (loading.value == true) {
      return
    }
    loading.value = true

    uni.showLoading({
      title: '支付处理中...'
    });

    try {
      // 从开发者服务器创建订单
      const orderId = await createOrder({
        productId: productId.value
      })
      // 请求苹果支付
      const transaction = await iap.requestPayment({
        productid: productId.value,
        manualFinishTransaction: true,
        username: orderId.order_id //根据业务需求透传参数，关联用户和订单关系
      })
      // 在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
      const res = await applepay({
        order_id: orderId.order_id,
        pay_time: transaction.transactionDate
      })
      // 验证成功后关闭订单
      await iap.finishTransaction(transaction);
      // 支付成功
    } catch (e) {
      if (e.code === 2) {
        uni.showModal({
          content: "取消支付",
          showCancel: false
        })
      }
    } finally {
      loading.value = false
      infoApi()
      uni.hideLoading()
    }

  })
  const createOrder = (async (productId) => {
    const res = await applePay({
      product_id: productId.productId
    })
    return res.data
  })
</script>

<style lang="scss" scoped>
  .wallet-page {
    display: flex;
    flex-direction: column;
    height: 100%;

    ::v-deep .u-navbar--fixed {
      position: sticky;
      box-sizing: border-box;
      background-color: #fff;
    }


    .wallet-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      width: 100%;
      border-radius: 32rpx 32rpx 0rpx 0rpx;
      background: linear-gradient(90deg, $color 0%, rgba(237, 225, 216, 1) 100%);
      margin-top: 24rpx;

      .content-head {
        height: 128rpx;
        width: 100%;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        padding: 0 64rpx 0 48rpx;

        .head-img {
          width: 48rpx;
          height: 48rpx;

        }

        .head-name {
          font-size: 32rpx;
          font-weight: 500;
          color: rgba(255, 255, 255, 1);
          margin-left: 12rpx;
          flex: 1;
        }

        .head-price {
          display: flex;
          font-size: 48rpx;
          font-weight: 400;
          align-items: baseline;
          color: rgba(51, 51, 51, 1);

          .price-label {
            font-size: 28rpx;

          }
        }
      }

      .content-nav {
        flex: 1;
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
        padding: 0 30rpx;
        border-radius: 32rpx 32rpx 0rpx 0rpx;
        background-color: #fff;

        .nav-prompt {
          margin-top: 30rpx;
          color: #666666;

          .prompt-title {
            font-size: 36rpx;
          }

          .prompt-nav {
            margin-top: 4rpx;
            font-size: 26rpx;
          }
        }

        .nav-title {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          height: 114rpx;

          .title-name {
            font-size: 28rpx;
            font-weight: 500;
            color: rgba(51, 51, 51, 1);

          }

          .title-label {
            font-size: 24rpx;
            font-weight: 400;
            color: rgba(245, 32, 32, 1);

          }
        }

        .nav-box {
          display: flex;
          flex-wrap: wrap;
          font-size: 32rpx;
          font-weight: 400;
          color: rgba(102, 102, 102, 1);
          justify-content: space-between;

          .box {
            width: 216rpx;
            height: 88rpx;
            border-radius: 20rpx;
            background: rgba(242, 242, 242, 1);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 24rpx;
            box-sizing: border-box;
          }

          .box-active {
            width: 216rpx;
            height: 88rpx;
            border-radius: 20rpx;
            background: rgba(248, 243, 239, 1);
            border: 2rpx solid rgba(164, 104, 47, 1);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 24rpx;
            box-sizing: border-box;
          }
        }

        .box-int {
          width: 100%;
          height: 88rpx;
          border-radius: 20rpx;
          background: rgba(242, 242, 242, 1);
          display: flex;
          align-items: center;
          margin-top: 24rpx;
          box-sizing: border-box;
          padding: 0 32rpx;
        }

        .content-pay {
          display: flex;
          flex-direction: column;

          .pay-nav {
            width: 100%;
            display: flex;
            height: 100rpx;
            align-items: center;
            border-radius: 20rpx;
            border: 2rpx solid #F2F2F2;
            box-sizing: border-box;
            padding: 0 32rpx;
            margin-top: 20rpx;

            .pay-icon {
              height: 48rpx;
              width: 48rpx;
              margin-right: 20rpx;
            }

            .pay-info {
              flex: 1;
              display: flex;
              align-items: baseline;
            }

            .pay-name {
              font-size: 28rpx;
              font-weight: 400;
              color: rgba(51, 51, 51, 1);

            }

            .pay-num {
              font-size: 26rpx;
              font-weight: 400;
              color: rgba(51, 51, 51, 1);
              margin-left: 12rpx;
            }

            .text-label {
              margin-left: 8rpx;
              font-size: 24rpx;
              color: $color;
            }
          }
        }

        .pay-btn {
          display: flex;
          flex-direction: column;
          position: fixed;
          bottom: 10rpx;
          left: 50%;
          transform: translate(-50%);
          box-sizing: border-box;
          padding: 0 40rpx;
          width: 100%;
          align-items: center;
          font-size: 22rpx;
          font-weight: 400;
          color: rgba(153, 153, 153, 1);

          ::v-deep .u-button--circle {
            margin-top: 32rpx;
          }

          .agreement-title {
            display: flex;
            align-items: center;
          }

          .agreement-label {
            color: $color;
          }
        }
      }
    }
  }
</style>